<template>
  <div :style="{ justifyContent: myDataList.length > 0 ? 'space-between' : 'flex-end' }" class="cardBox">
    <el-divider content-position="left">
      <span style="font-weight: bold">我的课程</span>
    </el-divider>
    <div v-for="item in myDataList" :key="item.id" class="cardItem" @click="toDetail(item.id)">
      <div class="cardItemTop">
        <img :src="item.cover ? item.cover : require('@/assets/dash/default.png')" class="itemImg" />
        <div class="cardItemTopRight">
          <div class="cardItemTopRightTime">
            <img src="@/assets/dash/time.png" />
            <span>{{ item.startTime }}</span>
            <el-dropdown v-permission="['course:delete']" trigger="hover" class="item-handle" @command="handleCommand">
              <i class="el-icon-s-tools" />
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="beforeHandleCommand(item.id, 'del')" icon="el-icon-delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
          <span class="cardTitle">{{ item.title }}</span>
        </div>
      </div>
      <!-- <div class="cardItemMiddle" v-html="formatQuestionContent(item.contentText)"></div> -->
      <div class="cardItemMiddle">
        {{ getTeacher(item.content) }}
      </div>
      <div class="cardItemBottom">
        <div class="itemProcess">
          <div :style="{ width: `${item.rate}%` }" class="itemProcessInner" />
        </div>
        <div class="processTxt">
          <img src="@/assets/dash/user.png" />
          <span>{{ item.passUser ? item.passUser : 0 }}/{{ item.totalUser == 0 || item.totalUser ? item.totalUser : 0 }}</span>
        </div>
      </div>
    </div>
    <div v-for="(item, index) in other" :key="'other_' + index" :style="{ marginLeft: myDataList.length > 0 ? '0' : '30px' }" class="iconBox" @click="toOther(item.pathName)">
      <img :src="item.icon" class="icon" />
      <span class="addTitle">{{ item.title }}</span>
    </div>
    <el-divider content-position="left">
      <span style="font-weight: bold">其他课程</span>
    </el-divider>
    <div v-for="item in otherDataList" :key="item.id" class="cardItem" @click="toCourse(item.id)">
      <div class="cardItemTop">
        <img :src="item.cover ? item.cover : require('@/assets/dash/default.png')" class="itemImg" />
        <div class="cardItemTopRight">
          <div class="cardItemTopRightTime">
            <img src="@/assets/dash/time.png" />
            <span>{{ item.startTime }}</span>
          </div>
          <span class="cardTitle">{{ item.title }}</span>
        </div>
      </div>
      <!-- <div class="cardItemMiddle" v-html="formatQuestionContent(item.contentText)"></div> -->
      <div class="cardItemMiddle">
        {{ getTeacher(item.content) }}
      </div>
      <div class="cardItemBottom">
        <div class="itemProcess">
          <div :style="{ width: `${item.rate}%` }" class="itemProcessInner" />
        </div>
        <div class="processTxt">
          <img src="@/assets/dash/user.png" />
          <span>{{ item.passUser ? item.passUser : 0 }}/{{ item.totalUser == 0 || item.totalUser ? item.totalUser : 0 }}</span>
        </div>
      </div>
    </div>
    <div class="moreBox" @click="toOther('ListCourse')">点击查看更多<img src="@/assets/dash/more.png" /></div>
  </div>
</template>
<script>
import { postData } from '@/api/common'
import { apiCourseOverview } from '@/api/stat/course'
import permission from '@/directive/permission/index.js' // 权限判断指令
export default {
  directives: { permission },
  data() {
    return {
      myDataList: [],
      otherDataList: [],
      other: [{ title: '添加课程', icon: require('@/assets/dash/add.png'), pathName: 'AddCourse' }],
      listQuery: {
        current: 1,
        size: 50,
        params: {
          title: ''
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 格式化试题内容JSON为友好显示格式
    formatQuestionContent(content) {
      if (!content) {
        return ''
      }

      // 如果内容以{开头，说明是JSON格式，需要进行格式化
      if (content.trim().startsWith('{')) {
        try {
          const parsedContent = JSON.parse(content)

          // 检查是否包含question字段
          if (parsedContent.question) {
            let formattedText = ''

            // 添加问题部分
            formattedText += `<strong>问题：</strong>${parsedContent.question}`

            // 根据题型添加不同的内容
            // 选择题：包含choose数组
            if (parsedContent.choose && Array.isArray(parsedContent.choose)) {
              formattedText += `<br/><strong>选项：</strong><br/>`
              parsedContent.choose.forEach(option => {
                formattedText += `• ${option}<br/>`
              })

              if (parsedContent.answer) {
                formattedText += `<strong>正确答案：</strong>${parsedContent.answer}`
              }
            }
            // 判断题：答案为布尔值或布尔字符串
            else if (typeof parsedContent.answer === 'boolean' || parsedContent.answer === 'true' || parsedContent.answer === 'false' || parsedContent.answer === '1' || parsedContent.answer === '0') {
              let isCorrect = false
              if (typeof parsedContent.answer === 'boolean') {
                isCorrect = parsedContent.answer
              } else if (parsedContent.answer === 'true' || parsedContent.answer === '1') {
                isCorrect = true
              } else {
                isCorrect = false
              }
              formattedText += `<br/><strong>答案：</strong>${isCorrect ? '正确' : '错误'}`
            }
            // 填空题：答案为数组
            else if (Array.isArray(parsedContent.answer)) {
              formattedText += `<br/><strong>参考答案：</strong>${parsedContent.answer.join('、')}`
            }
            // 简答题或其他：答案为字符串
            else if (parsedContent.answer) {
              formattedText += `<br/><strong>答案：</strong>${parsedContent.answer}`
            }

            return formattedText
          }
        } catch (e) {
          // JSON解析失败，直接返回原始内容
          return content
        }
      }

      // 如果不是JSON格式，直接返回原始内容
      return content
    },
    toCourse(id) {
      window.open('http://111.63.183.17:8082/#/web/course/view/' + id, '_blank')
    },
    toDetail(id) {
      this.$router.push({ name: 'UpdateCourse', params: { id: id } })
    },
    toOther(pathName) {
      this.$router.push({ name: pathName })
    },
    getList() {
      this.listQuery.t = new Date().getTime()
      postData('/api/course/course/paging', this.listQuery).then(response => {
        this.myDataList = []
        this.otherDataList = []
        response.data.records.map(item => {
          const statRes = this.getStat(item.id)
          if (statRes) {
            item.totalUser = statRes.totalUser
            item.passUser = statRes.passUser
            item.rate = statRes.passRate
          }
          if (item.isCurrentVisible == true) {
            this.myDataList.push(item)
          } else {
            this.otherDataList.push(item)
          }
        })
      })
    },
    async getStat(courseId) {
      try {
        const res = await apiCourseOverview(courseId)
        return res ? res.data : null
      } catch (err) {
        console.log('统计查询失败')
        return null
      }
    },
    beforeHandleCommand(id, name) {
      return {
        name: name,
        id
      }
    },
    handleCommand(e) {
      if (e.name == 'del') {
        this.delCourse(e.id)
      }
    },
    delCourse(id) {
      this.$confirm('确实要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        postData('/api/course/course/delete', { ids: [id] }).then(() => {
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
      })
    },
    getTeacher(str) {
      // 定义关键词
      const keyword = '授课教师：'
      // 找到关键词的位置
      const keywordIndex = str.indexOf(keyword)

      if (keywordIndex === -1) {
        return '未找到授课教师信息'
      }

      // 查找后续可能的结束标签（</p>、</strong>等）
      const endTag1 = str.indexOf('</p>', keywordIndex)
      const endTag2 = str.indexOf('</strong>', keywordIndex)
      const possibleEnds = [endTag1, endTag2].filter(pos => pos !== -1)

      if (possibleEnds.length === 0) {
        return '格式异常，无法提取'
      }

      // 取最早出现的结束标签位置
      const infoEnd = Math.min(...possibleEnds)

      // 提取从关键词开始到结束标签的完整内容
      return str.substring(keywordIndex, infoEnd).trim()
    }
  }
}
</script>
<style scoped lang="scss">
.el-divider__text {
  background-color: #f5f6fa !important; /* 设置背景透明 */
}
.el-divider {
  border: 1px solid #dcdfe6; /* 设置分割线的粗细和颜色 */
  font-weight: 700;
}
.cardBox {
  width: calc(100% + 30px);
  margin-top: 30px;
  color: #aab2c3;
  display: flex;
  align-items: center;
  justify-content: flex-start !important;
  flex-wrap: wrap;
  .cardItem {
    min-width: 300px;
    width: calc(25% - 30px);
    height: 225px;
    border-radius: 16px;
    font-size: 12px;
    background: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    cursor: pointer;
    position: relative;
    margin-right: 30px;
    margin-bottom: 30px;
    padding: 20px;
    box-sizing: border-box;
    .cardItemTop {
      display: flex;
      .itemImg {
        width: 80px;
        height: 92px;
        border-radius: 16px;
        object-fit: cover;
      }
      .cardItemTopRight {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        margin-left: 20px;
        padding: 4px 0;
        box-sizing: border-box;
        flex: 1;
        .cardItemTopRightTime {
          display: flex;
          align-items: center;
          position: relative;
          img {
            width: 14px;
            height: 14px;
            margin-right: 6px;
          }
          .item-handle {
            font-size: 16px;
            position: absolute;
            top: -12px;
            right: -10px;
            cursor: pointer;
          }
          .el-icon-s-tools {
            padding: 10px 10px 5px 10px;
          }
        }
        .cardTitle {
          margin-top: 10px;
          font-size: 18px;
          color: #140e35;
          font-weight: bold;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
    .cardItemMiddle {
      color: #565772;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    .cardItemBottom {
      height: 30px;
      display: flex;
      align-items: flex-end;
      justify-content: space-between;
      border-top: 1px solid #e3e3e3;
      .itemProcess {
        width: calc(100% - 70px);
        height: 8px;
        background: #f0f2f5;
        position: relative;
        .itemProcessInner {
          height: 8px;
          background: #4880ff;
          position: absolute;
          top: 0;
          left: 0;
        }
      }
      .processTxt {
        display: flex;
        align-items: center;
        img {
          width: 12px;
          height: 14px;
          margin-right: 6px;
        }
      }
    }
  }
  .iconBox {
    min-width: 300px;
    width: calc(25% - 30px);
    height: 225px;
    border-radius: 16px;
    color: #aab2c3;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    cursor: pointer;
    position: relative;
    margin-right: 30px;
    margin-bottom: 30px;
    .icon {
      width: 60px;
      height: 60px;
      margin-top: -20px;
    }
    .addTitle {
      position: absolute;
      top: calc(50% + 40px);
      left: 50%;
      transform: translateX(-50%);
    }
  }
  .moreBox {
    width: 100%;
    height: 50px;
    background: #fff;
    font-size: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    img {
      width: 20px;
      height: 20px;
      margin-left: 18px;
    }
  }
}
</style>
